package com.dengke.springsecurity.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;

import com.dengke.springsecurity.authentication.MyDBAuthenticationService;
import com.dengke.springsecurity.authentication.MyDbAuthenticationService4ShoppingCart;
@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

	@Autowired
	//MyDBAuthenticationService myDBAauthenticationService;
	MyDbAuthenticationService4ShoppingCart myDBAauthenticationService;

	//用户存储支撑验证过程
	@Autowired
	public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {

		// Users in memory.

//		auth.inMemoryAuthentication().withUser("user1").password("12345").roles("USER");
//		auth.inMemoryAuthentication().withUser("admin1").password("12345").roles("USER, ADMIN");

		// For User in database.
		auth.userDetailsService(myDBAauthenticationService);

	}

	//安全认证规则
	//
	@Override
	protected void configure(HttpSecurity http) throws Exception {
		http.csrf().disable();

		// The pages does not require login
		http.authorizeRequests().antMatchers("/", "/welcome", "/login", "/logout").permitAll();

		// /userInfo page requires login as USER or ADMIN.
		// If no login, it will redirect to /login page.
		http.authorizeRequests().antMatchers("/userInfo").access("hasAnyRole('ROLE_USER', 'ROLE_ADMIN')");

		// For ADMIN only.access(SpEl表达式计算结果为true时，允许访问)
		http.authorizeRequests().antMatchers("/admin").access("hasRole('ROLE_ADMIN')");

		// When the user has logged in as XX.
		// But access a page that requires role YY,
		// AccessDeniedException will throw.
		http.authorizeRequests().and().exceptionHandling().accessDeniedPage("/403");

		// Config for Login Form
		http.authorizeRequests().and().formLogin()//
				// Submit URL of login page.
				.loginProcessingUrl("/j_spring_security_check") // Submit URL,登录信息提交的URL
				.loginPage("/login")//登录页面
				.defaultSuccessUrl("/userInfo")//成功页面
				.failureUrl("/login?error=true")//失败页面
				.usernameParameter("username")//
				.passwordParameter("password")
				// Config for Logout Page
				.and().logout().logoutUrl("/logout").logoutSuccessUrl("/logoutSuccessful");
	}

}
